const state = {
  cartProducts: JSON.parse(localStorage.getItem('cart-products')) || []
}
const getters = {
  totalCount () {
    return state.cartProducts.reduce((sum, cur) => sum + cur.count, 0)
  },
  totalPrice () {
    return state.cartProducts.reduce((sum, cur) => sum + cur.totalPrice, 0)
  },
  checkedTotal () {
    return state.cartProducts.reduce((sum, cur) => {
      if (cur.isChecked) {
        sum += cur.count
      }
      return sum
    }, 0)
  },
  checkedTotalPrice () {
    return state.cartProducts.reduce((sum, cur) => {
      if (cur.isChecked) {
        sum += cur.totalPrice
      }
      return sum
    }, 0)
  }
}
const mutations = {
  addCart (state, product) {
    const prod = state.cartProducts.find(item => item.id === product.id)
    if (prod) {
      prod.count++
      prod.isChecked = true
      prod.totalPrice = prod.count * prod.price
    } else {
      state.cartProducts.push({
        ...product,
        count: 1,
        isChecked: true,
        totalPrice: product.price
      })
    }
  },
  // 改变商品数量
  changeProductCount (state, product) {
    const prod = state.cartProducts.find(item => item.id === product.id)
    prod && (prod.count = product.count)
    prod && (prod.totalPrice = product.count * product.price)
  },
  delProduct (state, id) {
    const index = state.cartProducts.findIndex(item => item.id === id)
    index !== -1 && state.cartProducts.splice(index, 1)
  },
  updateAllProductChecked (state, checked) {
    state.cartProducts.map(item => {
      item.isChecked = checked
    })
  },
  updateProductChecked (state, { checked, prodId }) {
    const prod = state.cartProducts.find(item => item.id === prodId)
    prod && (prod.isChecked = checked)
  }
}
const actions = {

}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
